package com.qinghe.plant.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.qinghe.plant.dao.Basemap;
import com.qinghe.plant.model.BasemapResponsitory;
import com.qinghe.plant.option.ManageOption;
import com.qinghe.plant.util.CodeType;
import com.qinghe.plant.util.ManageTool;
import com.qinghe.plant.util.Response;

@RestController
public class BasemapController{
	
	@Autowired
	private BasemapResponsitory basemapResponsitory;
	
	@RequestMapping(value="doReadBasemaps",method=RequestMethod.GET)
    public Response ReadBasemaps(HttpServletRequest request)
    {
		List<Basemap> basemaps=basemapResponsitory.findAll();
		return new Response(CodeType.Success,JSONArray.toJSONString(basemaps),"获取数据成功");		
	}
	
	@RequestMapping(value="doReadBasemap",method=RequestMethod.POST)
    public Response ReadBasemap(HttpServletRequest request)
    {
		Basemap basemap=FindBasemap(request.getParameter("id"));
		return new Response(CodeType.Success,JSONObject.toJSONString(basemap),"操作成功");	
	}
	
	@RequestMapping(value="doAlterBasemap",method=RequestMethod.POST)
	public Response AlterBasemap(HttpServletRequest request,MultipartFile bundle)
	{
		if(bundle.isEmpty())
		{
			return new Response(CodeType.Failed,null,"更新失败，请选择文件");
		}
		String fileName = bundle.getOriginalFilename();
		String filePath = ManageOption.Instant().getBasemapPath();		
		File file = new File(filePath + fileName);
		if(file.exists())
		{
			file.delete();
		}
		try 
		{
			bundle.transferTo(file);				
			Basemap basemap=JSONObject.parseObject(request.getParameter("basemap"),Basemap.class);
			basemap= basemapResponsitory.save(basemap);
			return new Response(CodeType.Success,JSONArray.toJSONString(basemap),"操作成功！");
		} catch (IOException e)
		{
			if(file.exists())
				file.delete();
			return new Response(CodeType.Failed,null,"上传失败");
		}
	}

	@RequestMapping(value="doInsertBasemap",method=RequestMethod.POST)
	public Response InsertBasemap(HttpServletRequest request,MultipartFile bundle)
	{		
		if (bundle.isEmpty()) {
			return new Response(CodeType.Failed,null,"上传失败，请选择文件");
		}
		
		String fileName = bundle.getOriginalFilename();
		String filePath = ManageOption.Instant().getBasemapPath();		
		File file = new File(filePath + fileName);
		if(file.exists())
		{
			return new Response(CodeType.Failed,null,"文件已存在");
		}
		else
		{
			try 
			{
				bundle.transferTo(file);				
				Basemap basemap=new Basemap();
				basemap.setName(request.getParameter("name"));
				basemap.setX(Double.parseDouble(request.getParameter("x")) );
				basemap.setY(Double.parseDouble( request.getParameter("y")));
				basemap.setBundle(fileName);
				basemap.setAssemblies(request.getParameter("assemblies"));
				basemap.setCreator(request.getParameter("creator"));
				basemap.setTimer(new Date());
				basemap= basemapResponsitory.save(basemap);
				return new Response(CodeType.Success,JSONObject.toJSONString(basemap),"操作成功！");	
			} catch (IOException e)
			{
				if(file.exists())
					file.delete();
				return new Response(CodeType.Failed,null,"上传失败");
			}
		}
	}	
	
	@RequestMapping(value="doDeleteBasemap",method=RequestMethod.POST)
	public Response DeleteBasemap(HttpServletRequest request){
		
		Basemap basemap=JSONObject.parseObject(request.getParameter("basemap"),Basemap.class);
		basemapResponsitory.deleteById(basemap.getId());
		
		String fileName =basemap.getBundle();
		String filePath = ManageOption.Instant().getBasemapPath();		
		File file = new File(filePath + fileName);
		if(file.exists())
		{
			file.delete();
		}
		return new Response(CodeType.Success,null,"操作成功！");		
	}
	
	@RequestMapping(value="doDownloadBasemap",method= {RequestMethod.POST})
	public void DownloadBasemap(HttpServletRequest request, HttpServletResponse response) throws IOException
	{		 
		String fileName=request.getParameter("fileName");
		String filePath=ManageOption.Instant().getBasemapPath();
		
		//获取输出流
        OutputStream out=response.getOutputStream();
        //把文件变成byte字节流传入输出流
        out.write(ManageTool.GetBytes(filePath+fileName));
        //刷新流
        out.flush();
        //关闭流
        out.close();
        //向控制台提示成功
        System.out.println("success!");
 
    }	
	
	private Basemap FindBasemap(String id) {
		@SuppressWarnings("serial")
		List<Basemap> result = basemapResponsitory.findAll(new Specification<Basemap>() {
			@Override
			public Predicate toPredicate(Root<Basemap> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				list.add(cb.equal(root.get("id").as(String.class), id));
				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}
		});
		return (result!=null)?result.get(0):null;
	}

}
